package com.kd.juhaowan.ui.holder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.flyjingfish.shapeimageviewlib.ShapeImageView;

import com.kd.juhaowan.R;
import com.kd.juhaowan.http.model.CommentModel;
import com.kd.juhaowan.http.model.SubCommentModel;
import com.kd.juhaowan.ui.adapter.BaseRecyclerViewAdapter;
import com.kd.juhaowan.ui.adapter.BaseViewHolder;
import com.kd.juhaowan.ui.listener.OnItemClickListener;
import com.kd.juhaowan.ui.listener.OnItemDianzanListener;
import com.kd.juhaowan.utils.GlideHelper;
import com.kd.juhaowan.utils.LogUtil;
import com.kd.juhaowan.view.CommentImageView;
import com.kd.juhaowan.view.RecycleViewForScrollView;
import com.luck.picture.lib.entity.LocalMedia;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class CommentViewHolder extends BaseViewHolder {



    @BindView(R.id.item_avatar)
    ShapeImageView iconView;

    @BindView(R.id.item_name)
    TextView nameView;


    @BindView(R.id.item_level)
    TextView levelView;


    @BindView(R.id.item_dianzan)
    TextView dianzanView;
    @BindView(R.id.item_pinglun)
    TextView pinglunView;


    @BindView(R.id.item_content)
    TextView contentView;
//    @BindView(R.id.item_images)
//    RelativeLayout imageLayout;
    @BindView(R.id.item_subComment)
    LinearLayout subCommentLayout;
    @BindView(R.id.item_subComment_list)
    RecycleViewForScrollView subCommentList;
    private BaseRecyclerViewAdapter<BaseViewHolder, SubCommentModel> giftAdapter;

    @BindView(R.id.subcomment_more)
    TextView subCommentMore;
    @BindView(R.id.item_diver)
    View diverView;
    @BindView(R.id.item_ratingbar)
    RatingBar ratingBar;

//    @BindView(R.id.subcomment_child1)
//    TextView subcomment1;
//    @BindView(R.id.subcomment_child2)
//    TextView subcomment2;
//    @BindView(R.id.subcomment_child3)
//    TextView subcomment3;
//    @BindView(R.id.subcomment_child4)
//    TextView subcomment4;





    @BindView(R.id.item_time)
    TextView timeView;
    @BindView(R.id.item_location)
    TextView addrView;


    private View.OnClickListener contentListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            OnItemClickListener listener = getOnItemClickListener();
            listener.onItemClick(CommentViewHolder.this,contentView,getLayoutPosition());
        }
    };


    public CommentViewHolder(@NonNull View itemView) {
        super(itemView);

        giftAdapter = new BaseRecyclerViewAdapter<BaseViewHolder, SubCommentModel>() {
            @NonNull
            @Override
            public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                BaseViewHolder holder;
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                if(viewType==0){
                    View view = inflater.inflate(R.layout.item_comment_sub, parent, false);
                    holder=new CommentSubViewHolder(view);
                }else if (viewType==1){
                    View view = inflater.inflate(R.layout.item_comment_sub_one, parent, false);
                    holder=new CommentSubViewHolderOnePic(view);
                }else if (viewType ==2){
                    View view = inflater.inflate(R.layout.item_comment_sub_two, parent, false);
                    holder=new CommentSubViewHolderTwoPic(view);
                }else {
                    View view = inflater.inflate(R.layout.item_comment_sub_three, parent, false);
                    holder=new CommentSubViewHolderThreePic(view);
                }
//                holder.setOnItemClickListener(getOnItemClickListener());
                return  holder;

            }

            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {

                if(holder instanceof CommentSubViewHolder){
                    ((CommentSubViewHolder)holder).setDate(getItem(position));
                }else if (holder instanceof CommentSubViewHolderOnePic){
                    ((CommentSubViewHolderOnePic)holder).setDate(getItem(position));
                }else if (holder instanceof CommentSubViewHolderTwoPic){
                    ((CommentSubViewHolderTwoPic)holder).setDate(getItem(position));
                }else if (holder instanceof CommentSubViewHolderThreePic){
                    ((CommentSubViewHolderThreePic)holder).setDate(getItem(position));
                }

            }
            @Override
            public int getItemViewType(int position) {
                SubCommentModel model =giftAdapter.getItem(position);
                String[] images = model.getImages();
                if(images==null||images.length==0){
                    return 0;
                }else {
                    return images.length>=3?3:images.length;
                }

            }
        };
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        layoutManager.setOrientation(RecyclerView.VERTICAL);
//        DividerItemDecoration decoration = new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL);
//        decoration.setDrawable(getContext().getDrawable(R.drawable.listview_diver));
//        giftListView.addItemDecoration(decoration);
        subCommentList.setLayoutManager(layoutManager);
        subCommentList.setAdapter(giftAdapter);
    }

    @OnClick(R.id.item_dianzan)
    void onDianzanClick(){
        OnItemClickListener listener = getOnItemClickListener();
        if(listener instanceof OnItemDianzanListener){
            ((OnItemDianzanListener) listener).onItemDianzanClick(CommentViewHolder.this,getLayoutPosition());
        }
    }
    @OnClick(R.id.item_subComment_list)
    void onChildCLick(){
        OnItemClickListener listener = getOnItemClickListener();
        listener.onItemClick(null,null,getLayoutPosition());
    }

    private SpannableString getSpanString(SubCommentModel model){
         String temp = model.getUser_text().getNickname();
//         if(model.getIs_author()==1){
//             temp+=" 楼主 ";
//         }
         if(model.getUser_reply_text()!=null&&!TextUtils.isEmpty(model.getUser_reply_text().getNickname())){
             temp+="回复@"+model.getUser_reply_text().getNickname()+" ";
         }
         temp+="："+model.getContent();
         SpannableString spannableString = new SpannableString(temp);
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#603FE0")), temp.indexOf(model.getUser_text().getNickname()), temp.indexOf(model.getUser_text().getNickname())+model.getUser_text().getNickname().length(), 0);
//        if(model.getIs_author()==1){
//            temp+=" 楼主 ";
//            spannableString.setSpan(new AbsoluteSizeSpan(10,true), temp.indexOf("楼主"), temp.indexOf("楼主")+2, 0);
//            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#898A8F")), temp.indexOf("楼主"), temp.indexOf("楼主")+2, 0);
//        }

        if(model.getUser_reply_text()!=null&&!TextUtils.isEmpty(model.getUser_reply_text().getNickname())){
            LogUtil.debugLog("name"+model.getUser_reply_text().getNickname());
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#603FE0")), temp.indexOf("回复")+2, temp.lastIndexOf(model.getUser_reply_text().getNickname())+model.getUser_reply_text().getNickname().length(), 0);
        }
        LogUtil.debugLog(model.toString()+"\n"+spannableString);
         return spannableString;
    }

    class ViewHolder {
        TextView content;
        RelativeLayout childImageView;
    }
    private ArrayList<LocalMedia> mediaList=new ArrayList<>();

    @SuppressLint("ResourceType")
    private void setImageLayout(String[] images, boolean isChild, RelativeLayout iamgeLayout){
        if (images==null||images.length==0){

            iamgeLayout.setVisibility(View.GONE);

        }else if (images.length==1){
            if(!isChild){
                mediaList.add(LocalMedia.generateHttpAsLocalMedia(images[0]));

            }
            iamgeLayout.setVisibility(View.VISIBLE);
            iamgeLayout.removeAllViews();
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT, UIUtil.dip2px(getContext(),isChild?140:178));
            lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            CommentImageView imageView = new CommentImageView(getContext());
//            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if(!isChild){
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GlideHelper.imagePreview((Activity) getContext(),0,mediaList);
                    }
                });
            }
            imageView.setScaleType(ImageView.ScaleType.FIT_START);
            GlideHelper.loadGoodsCover(Glide.with(getItemView()),imageView,images[0]);
            iamgeLayout.addView(imageView,lp1);
        }else if (images.length==2){
            for (String image:images) {
                if(!isChild){
                    mediaList.add(LocalMedia.generateHttpAsLocalMedia(image));
                }
            }
            iamgeLayout.setVisibility(View.VISIBLE);
            iamgeLayout.removeAllViews();
            int iconWidth = (UIUtil.getScreenWidth(getContext())-UIUtil.dip2px(getContext(),isChild?70:50)-UIUtil.dip2px(getContext(),20))/2;
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                     iconWidth,UIUtil.dip2px(getContext(),isChild?100:111));
            lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            CommentImageView imageView = new CommentImageView(getContext());
//            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if(!isChild){
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GlideHelper.imagePreview((Activity) getContext(),0,mediaList);
                    }
                });
            }

            GlideHelper.loadGoodsCover(Glide.with(getItemView()),imageView,images[0]);
            CommentImageView imageView2 = new CommentImageView(getContext());

            if(!isChild){
                imageView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GlideHelper.imagePreview((Activity) getContext(),1,mediaList);
                    }
                });
            }
            GlideHelper.loadGoodsCover(Glide.with(getItemView()),imageView2,images[1]);
            iamgeLayout.addView(imageView,lp1);
            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                    iconWidth, UIUtil.dip2px(getContext(),isChild?100:111));
            lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            iamgeLayout.addView(imageView2,lp2);

        }else if(images.length>2){
            for (String image:images) {
                if(!isChild){
                    mediaList.add(LocalMedia.generateHttpAsLocalMedia(image));
                }
            }
            iamgeLayout.setVisibility(View.VISIBLE);
            iamgeLayout.removeAllViews();
            int iconWidth = (UIUtil.getScreenWidth(getContext())-UIUtil.dip2px(getContext(),isChild?70:50)-UIUtil.dip2px(getContext(),isChild?8:10))/3;
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                    iconWidth, iconWidth);
            lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            ImageView imageView = new ImageView(getContext());
            if(!isChild){
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GlideHelper.imagePreview((Activity) getContext(),0,mediaList);
                    }
                });
            }

            GlideHelper.loadGoodsCover(Glide.with(getItemView()),imageView,images[0]);
            ImageView imageView2 = new ImageView(getContext());
            if(!isChild){
                imageView2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        GlideHelper.imagePreview((Activity) getContext(),1,mediaList);
                    }
                });
            }
            GlideHelper.loadGoodsCover(Glide.with(getItemView()),imageView2,images[1]);
            iamgeLayout.addView(imageView,lp1);
            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                    iconWidth, iconWidth);
            lp2.addRule(RelativeLayout.CENTER_IN_PARENT);


            iamgeLayout.addView(imageView2,lp2);
            if(images.length>=3){

                ImageView imageView3 = new ImageView(getContext());
                imageView3.setId(isChild?222222:11111);
                if(!isChild){
                    imageView3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GlideHelper.imagePreview((Activity) getContext(),2,mediaList);
                        }
                    });
                }

                GlideHelper.loadGoodsCover(Glide.with(getItemView()),imageView3,images[2]);
                RelativeLayout.LayoutParams lp3 = new RelativeLayout.LayoutParams(
                        iconWidth, iconWidth);
                lp3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                iamgeLayout.addView(imageView3,lp3);
                if(images.length>3){
                    RelativeLayout.LayoutParams lptv = new RelativeLayout.LayoutParams(
                            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lptv.addRule(RelativeLayout.ALIGN_BOTTOM,isChild?222222:11111);
                    lptv.addRule(RelativeLayout.ALIGN_RIGHT,isChild?222222:11111);
                    TextView tv =new TextView(getContext());
                    tv.setText("+"+(images.length-3));
                    tv.setPadding(8,4,8,4);
                    tv.setTextSize(10);
                    tv.setTextColor(getContext().getColor(R.color.white));
                    tv.setBackgroundColor(getContext().getColor(R.color.image_more_bg));
                    iamgeLayout.addView(tv,lptv);
                }
            }
        }
    }


    @SuppressLint("ResourceType")
    public void setDate(CommentModel model, int position, boolean isLast){
        mediaList.clear();
//        bankName.setText(model.getName());
//        diverView.setVisibility(isLast?View.GONE:View.VISIBLE);
        LogUtil.debugLog(position+".."+isLast+"..");
        diverView.setBackgroundColor(isLast?getContext().getColor(R.color.white):getContext().getColor(R.color.cE2));
        ratingBar.setRating(Float.parseFloat(model.getNumber_stars()));
        GlideHelper.loadGoodsCover(Glide.with(getItemView()),iconView,model.getUser_text().getAvatar());
        nameView.setText(model.getUser_text().getNickname());
        levelView.setText("Lv"+model.getUser_text().getLevel());

        contentView.setText(model.getContent());
//        contentView.setMovementMethod(LinkMovementMethod.getInstance());
//        contentView.setClickable(true);
//        contentView.setOnClickListener(contentListener);
//        contentView.setText(AtUserHelper.parseAtUserLink(model.getContent(),getContext()));
        dianzanView.setText(model.getLike_count()+"");
        pinglunView.setText(model.getReply_comment_total()+"");
        timeView.setText(model.getCreatetime().contains(" ")?model.getCreatetime().substring(0,model.getCreatetime().indexOf(" ")):model.getCreatetime());

        addrView.setText(model.getPlaceof_posting());
        int subsize=model.getReply_comment_total();
        if(subsize==0){
            subCommentLayout.setVisibility(View.GONE);
        }else {
            subCommentLayout.setVisibility(View.VISIBLE);
            giftAdapter.resetAdapterData(model.getSub_comment());
//            subCommentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                    OnItemClickListener listener = getOnItemClickListener();
//                    listener.onItemClick(null,null,position);
//                }
//            });
//            subCommentList.setAdapter(new BaseAdapter() {
//                @Override
//                public int getCount() {
//                    return subsize>3?3:subsize;
//                }
//
//                @Override
//                public Object getItem(int i) {
//                    return model.getSub_comment().get(i);
//                }
//
//                @Override
//                public long getItemId(int i) {
//                    return i;
//                }
//
//                @Override
//                public View getView(int i, View convertView, ViewGroup viewGroup) {
//                    ViewHolder viewHolder = null;
//                    if (convertView == null) {
//                        viewHolder = new ViewHolder();
//                        convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_comment_sub,null,false);
//
//                        viewHolder.content =convertView.findViewById(R.id.subcomment_child);
//                        viewHolder.childImageView =convertView.findViewById(R.id.subcomment_images);
//                        convertView.setTag(viewHolder);
//                    }else {
//                        viewHolder = (ViewHolder) convertView.getTag();
//                    }
//
//                    viewHolder.content.setText(getSpanString(model.getSub_comment().get(i)));
//                    String[] img=model.getSub_comment().get(i).getImages();
//                    setImageLayout(img,true,viewHolder.childImageView);
//                    return convertView;
//                }
//            });
            if(subsize>3){
                subCommentMore.setVisibility(View.VISIBLE);
                subCommentMore.setText("查看全部"+subsize+"条评论");
//                subcomment4.setVisibility(View.VISIBLE);
//                subcomment3.setVisibility(View.VISIBLE);
//                subcomment2.setVisibility(View.VISIBLE);
//                subcomment3.setText(getSpanString(model.getSub_comment().get(2)));
//                subcomment2.setText(getSpanString(model.getSub_comment().get(1)));
//                subcomment1.setText(getSpanString(model.getSub_comment().get(0)));
            }else {
                subCommentMore.setVisibility(View.GONE);


//                SpannableString spannableString = new SpannableString("我是一段需要被修饰的字符串");
//                ImageSpan imageSpan = new ImageSpan(getContext(), R.drawable.dm_level_bg);
//                spannableString.setSpan(imageSpan, 4, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//                subcomment1.setText(getSpanString(model.getSub_comment().get(0)));
//
//                if(subsize>2){
//                    subcomment3.setVisibility(View.VISIBLE);
//                    subcomment3.setText(getSpanString(model.getSub_comment().get(2)));
//                }else {
//                    subcomment3.setVisibility(View.GONE);
//                }
//                if(subsize>1){
//                    subcomment2.setVisibility(View.VISIBLE);
//                    subcomment2.setText(getSpanString(model.getSub_comment().get(1)));
//                }else {
//                    subcomment2.setVisibility(View.GONE);
//
//                }
            }
        }
        dianzanView.setCompoundDrawablePadding(UIUtil.dip2px(getContext(),5));
        if(model.getIs_like()==1){
            dianzanView.setCompoundDrawablesWithIntrinsicBounds(getContext().getDrawable(R.mipmap.icon_dianzan_self),null,null,null);

        }else {
            dianzanView.setCompoundDrawablesWithIntrinsicBounds(getContext().getDrawable(R.mipmap.icon_dianzan_default),null,null,null);

        }
//        imageLayout.removeAllViews();
//        mediaList.clear();

//            String[] images= model.getImages();
//        setImageLayout(images,false,imageLayout);
//            LogUtil.debugLog((images==null)+"");


        }
    }



